<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\assistant;

use app\common\manager\BaseManager;
use think\Db;
use think\Exception;

class AssistantMoneyManager extends BaseManager
{
    CONST TYPE_INCREASE = 2;
    CONST TYPE_DECREASE = 1;

    /**
     * 金额变动类型 :
     * 1 = 冻结
     * 2 = 提现
     * 3 = 组队
     * 4 = 解冻返回
     */
    CONST TYPE_FREEZE = 1;
    CONST TYPE_WITHDRAWAL = 2;
    CONST TYPE_TEAM = 3;
    CONST TYPE_UNFREEZE_RETURN = 4;

    CONST TYPE_FREEZE_MESSAGE = '用户%s 于 %s 提现冻结 %.2f';
    CONST TYPE_WITHDRAWAL_MESSAGE = '用户%s 于 %s 提现 %.2f';
    CONST TYPE_INCREASE_TEAM_MESSAGE = '用户%s 于 %s 组队成功,收入%.2f';
    CONST TYPE_DECREASE_TEAM_MESSAGE = '用户%s 于 %s 参与组队,支出%.2f';
    CONST TYPE_UNFREEZE_RETURN_MESSAGE = '用户%s 于 %s 解冻返回余额 %.2f';

    /**
     * @param object $assistantAccount 助教账户
     * @param int $userId 用户id
     * @param float $money 金额
     * @param int $outIn 1=收入,2=支出
     * @param int $detail 1=冻结 2=提现 3=组队 4=解冻返回
     * @param string $message 消息
     * @param array $extend 扩展字段
     * @param boolean $trans 是否开启事务
     * @return void
     */
    public static function UserMoneyLog(object $assistantAccount,int $userId, float $money,int $outIn,int $detail,string $message,array $extend=[],bool $trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            \app\common\model\assistant\Moneylog::create([
                'assistant_id' => $assistantAccount->assistant_id,
                'user_id' => $userId,
                'type' => $outIn,
                'detail' => $detail,
                'money' => $money,
                'before' => $assistantAccount->total,
                'after' => bcadd($assistantAccount->total,$money,2),
                'memo' => $message,
                'relation_id' => $extend['relation_id'] ?? 0,
                'relation_order' => $extend['relation_order'] ?? '',
                'createtime' => time(),
            ]);

            if ($trans){
                Db::commit();
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }
}